a26ef68609e505438444a8d1dd0fdecb27aa6524
3 * Base class and functions for profiling.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
22 * This file is only included if profiling is enabled
26 * @defgroup Profiler Profiler
30 * Begin profiling of a function
31 * @param string $functionname name of the function we will profile
33 function wfProfileIn( $functionname ) {
34 if ( Profiler
::$__instance === null ) { // use this directly to reduce overhead
37 if ( !( Profiler
::$__instance instanceof ProfilerStub
) ) {
38 Profiler
::$__instance->profileIn( $functionname );
43 * Stop profiling of a function
44 * @param string $functionname name of the function we have profiled
46 function wfProfileOut( $functionname = 'missing' ) {
47 if ( Profiler
::$__instance === null ) { // use this directly to reduce overhead
50 if ( !( Profiler
::$__instance instanceof ProfilerStub
) ) {
51 Profiler
::$__instance->profileOut( $functionname );
56 * Class for handling function-scope profiling
60 class ProfileSection
{
61 protected $name; // string; method name
62 protected $enabled = false; // boolean; whether profiling is enabled
65 * Begin profiling of a function and return an object that ends profiling of
66 * the function when that object leaves scope. As long as the object is not
67 * specifically linked to other objects, it will fall out of scope at the same
68 * moment that the function to be profiled terminates.
70 * This is typically called like:
71 * <code>$section = new ProfileSection( __METHOD__ );</code>
73 * @param string $name Name of the function to profile
75 public function __construct( $name ) {
77 if ( Profiler
::$__instance === null ) { // use this directly to reduce overhead
80 if ( !( Profiler
::$__instance instanceof ProfilerStub
) ) {
81 $this->enabled
= true;
82 Profiler
::$__instance->profileIn( $this->name
);
86 function __destruct() {
87 if ( $this->enabled
) {
88 Profiler
::$__instance->profileOut( $this->name
);
98 protected $mStack = array(), $mWorkStack = array(), $mCollated = array(),
99 $mCalls = array(), $mTotals = array();
100 protected $mTimeMetric = 'wall';
101 protected $mProfileID = false, $mCollateDone = false, $mTemplated = false;
103 protected $mDBLockThreshold = 5.0; // float; seconds
104 /** @var Array DB/server name => (active trx count,timestamp) */
105 protected $mDBTrxHoldingLocks = array();
106 /** @var Array DB/server name => list of (method, elapsed time) */
107 protected $mDBTrxMethodTimes = array();
110 public static $__instance = null; // do not call this outside Profiler and ProfileSection
112 function __construct( $params ) {
113 if ( isset( $params['timeMetric'] ) ) {
114 $this->mTimeMetric
= $params['timeMetric'];
116 if ( isset( $params['profileID'] ) ) {
117 $this->mProfileID
= $params['profileID'];
120 $this->addInitialStack();
127 public static function instance() {
128 if ( self
::$__instance === null ) {
130 if ( is_array( $wgProfiler ) ) {
131 if ( !isset( $wgProfiler['class'] ) ) {
132 $class = 'ProfilerStub';
134 $class = $wgProfiler['class'];
136 self
::$__instance = new $class( $wgProfiler );
137 } elseif ( $wgProfiler instanceof Profiler
) {
138 self
::$__instance = $wgProfiler; // back-compat
140 self
::$__instance = new ProfilerStub( $wgProfiler );
143 return self
::$__instance;
147 * Set the profiler to a specific profiler instance. Mostly for dumpHTML
148 * @param $p Profiler object
150 public static function setInstance( Profiler
$p ) {
151 self
::$__instance = $p;
155 * Return whether this a stub profiler
159 public function isStub() {
164 * Return whether this profiler stores data
166 * @see Profiler::logData()
169 public function isPersistent() {
173 public function setProfileID( $id ) {
174 $this->mProfileID
= $id;
177 public function getProfileID() {
178 if ( $this->mProfileID
=== false ) {
181 return $this->mProfileID
;
186 * Add the inital item in the stack.
188 protected function addInitialStack() {
189 // Push an entry for the pre-profile setup time onto the stack
190 $initial = $this->getInitialTime();
191 if ( $initial !== null ) {
192 $this->mWorkStack
[] = array( '-total', 0, $initial, 0 );
193 $this->mStack
[] = array( '-setup', 1, $initial, 0, $this->getTime(), 0 );
195 $this->profileIn( '-total' );
200 * Called by wfProfieIn()
202 * @param $functionname String
204 public function profileIn( $functionname ) {
205 global $wgDebugFunctionEntry;
206 if ( $wgDebugFunctionEntry ) {
207 $this->debug( str_repeat( ' ', count( $this->mWorkStack
) ) . 'Entering ' . $functionname . "\n" );
210 $this->mWorkStack
[] = array( $functionname, count( $this->mWorkStack
), $this->getTime(), memory_get_usage() );
214 * Called by wfProfieOut()
216 * @param $functionname String
218 public function profileOut( $functionname ) {
219 global $wgDebugFunctionEntry;
220 $memory = memory_get_usage();
221 $time = $this->getTime();
223 if ( $wgDebugFunctionEntry ) {
224 $this->debug( str_repeat( ' ', count( $this->mWorkStack
) - 1 ) . 'Exiting ' . $functionname . "\n" );
227 $bit = array_pop( $this->mWorkStack
);
230 $this->debugGroup( 'profileerror', "Profiling error, !\$bit: $functionname" );
232 if ( $functionname == 'close' ) {
233 if ( $bit[0] != '-total' ) {
234 $message = "Profile section ended by close(): {$bit[0]}";
235 $this->debugGroup( 'profileerror', $message );
236 $this->mStack
[] = array( $message, 0, 0.0, 0, 0.0, 0 );
238 } elseif ( $bit[0] != $functionname ) {
239 $message = "Profiling error: in({$bit[0]}), out($functionname)";
240 $this->debugGroup( 'profileerror', $message );
241 $this->mStack
[] = array( $message, 0, 0.0, 0, 0.0, 0 );
245 $this->mStack
[] = $bit;
246 $this->updateTrxProfiling( $functionname, $time );
251 * Close opened profiling sections
253 public function close() {
254 while ( count( $this->mWorkStack
) ) {
255 $this->profileOut( 'close' );
260 * Mark a DB as in a transaction with one or more writes pending
262 * Note that there can be multiple connections to a single DB.
264 * @param string $server DB server
265 * @param string $db DB name
267 public function transactionWritingIn( $server, $db ) {
268 $name = "{$server} ({$db})";
269 if ( isset( $this->mDBTrxHoldingLocks
[$name] ) ) {
270 ++
$this->mDBTrxHoldingLocks
[$name]['refs'];
272 $this->mDBTrxHoldingLocks
[$name] = array( 'refs' => 1, 'start' => microtime( true ) );
273 $this->mDBTrxMethodTimes
[$name] = array();
278 * Register the name and time of a method for slow DB trx detection
280 * @param string $method Function name
281 * @param float $realtime Wal time ellapsed
283 protected function updateTrxProfiling( $method, $realtime ) {
284 if ( !$this->mDBTrxHoldingLocks
) {
285 return; // short-circuit
286 // @TODO: hardcoded check is a tad janky (what about FOR UPDATE?)
287 } elseif ( !preg_match( '/^query-m: (?!SELECT)/', $method )
288 && $realtime < $this->mDBLockThreshold
290 return; // not a DB master query nor slow enough
292 $now = microtime( true );
293 foreach ( $this->mDBTrxHoldingLocks
as $name => $info ) {
294 // Hacky check to exclude entries from before the first TRX write
295 if ( ( $now - $realtime ) >= $info['start'] ) {
296 $this->mDBTrxMethodTimes
[$name][] = array( $method, $realtime );
302 * Mark a DB as no longer in a transaction
304 * This will check if locks are possibly held for longer than
305 * needed and log any affected transactions to a special DB log.
306 * Note that there can be multiple connections to a single DB.
308 * @param string $server DB server
309 * @param string $db DB name
311 public function transactionWritingOut( $server, $db ) {
312 $name = "{$server} ({$db})";
313 if ( --$this->mDBTrxHoldingLocks
[$name]['refs'] <= 0 ) {
315 foreach ( $this->mDBTrxMethodTimes
[$name] as $info ) {
316 list( $method, $realtime ) = $info;
317 if ( $realtime >= $this->mDBLockThreshold
) {
323 $dbs = implode( ', ', array_keys( $this->mDBTrxHoldingLocks
) );
324 $msg = "Sub-optimal transaction on DB(s) {$dbs}:\n";
325 foreach ( $this->mDBTrxMethodTimes
[$name] as $i => $info ) {
326 list( $method, $realtime ) = $info;
327 $msg .= sprintf( "%d\t%.6f\t%s\n", $i, $realtime, $method );
329 $this->debugGroup( 'DBPerformance', $msg );
331 unset( $this->mDBTrxHoldingLocks
[$name] );
332 unset( $this->mDBTrxMethodTimes
[$name] );
337 * Mark this call as templated or not
341 function setTemplated( $t ) {
342 $this->mTemplated
= $t;
346 * Returns a profiling output to be stored in debug file
350 public function getOutput() {
351 global $wgDebugFunctionEntry, $wgProfileCallTree;
352 $wgDebugFunctionEntry = false;
354 if ( !count( $this->mStack
) && !count( $this->mCollated
) ) {
355 return "No profiling output\n";
358 if ( $wgProfileCallTree ) {
359 return $this->getCallTree();
361 return $this->getFunctionReport();
366 * Returns a tree of function call instead of a list of functions
369 function getCallTree() {
370 return implode( '', array_map( array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->mStack
) ) );
374 * Recursive function the format the current profiling array into a tree
376 * @param array $stack profiling array
379 function remapCallTree( $stack ) {
380 if ( count( $stack ) < 2 ) {
384 for ( $max = count( $stack ) - 1; $max > 0; ) {
385 /* Find all items under this entry */
386 $level = $stack[$max][1];
388 for ( $i = $max -1; $i >= 0; $i-- ) {
389 if ( $stack[$i][1] > $level ) {
390 $working[] = $stack[$i];
395 $working = $this->remapCallTree( array_reverse( $working ) );
397 foreach ( $working as $item ) {
398 array_push( $output, $item );
400 array_unshift( $output, $stack[$max] );
403 array_unshift( $outputs, $output );
406 foreach ( $outputs as $output ) {
407 foreach ( $output as $item ) {
415 * Callback to get a formatted line for the call tree
418 function getCallTreeLine( $entry ) {
419 list( $fname, $level, $start, /* $x */, $end ) = $entry;
420 $delta = $end - $start;
421 $space = str_repeat( ' ', $level );
422 # The ugly double sprintf is to work around a PHP bug,
423 # which has been fixed in recent releases.
424 return sprintf( "%10s %s %s\n", trim( sprintf( "%7.3f", $delta * 1000.0 ) ), $space, $fname );
428 * Get the initial time of the request, based either on $wgRequestTime or
429 * $wgRUstart. Will return null if not able to find data.
431 * @param string|false $metric metric to use, with the following possibilities:
432 * - user: User CPU time (without system calls)
433 * - cpu: Total CPU time (user and system calls)
434 * - wall (or any other string): elapsed time
435 * - false (default): will fall back to default metric
438 function getTime( $metric = false ) {
439 if ( $metric === false ) {
440 $metric = $this->mTimeMetric
;
443 if ( $metric === 'cpu' ||
$this->mTimeMetric
=== 'user' ) {
444 if ( !function_exists( 'getrusage' ) ) {
448 $time = $ru['ru_utime.tv_sec'] +
$ru['ru_utime.tv_usec'] / 1e6
;
449 if ( $metric === 'cpu' ) {
450 # This is the time of system calls, added to the user time
451 # it gives the total CPU time
452 $time +
= $ru['ru_stime.tv_sec'] +
$ru['ru_stime.tv_usec'] / 1e6
;
456 return microtime( true );
461 * Get the initial time of the request, based either on $wgRequestTime or
462 * $wgRUstart. Will return null if not able to find data.
464 * @param string|false $metric metric to use, with the following possibilities:
465 * - user: User CPU time (without system calls)
466 * - cpu: Total CPU time (user and system calls)
467 * - wall (or any other string): elapsed time
468 * - false (default): will fall back to default metric
471 protected function getInitialTime( $metric = false ) {
472 global $wgRequestTime, $wgRUstart;
474 if ( $metric === false ) {
475 $metric = $this->mTimeMetric
;
478 if ( $metric === 'cpu' ||
$this->mTimeMetric
=== 'user' ) {
479 if ( !count( $wgRUstart ) ) {
483 $time = $wgRUstart['ru_utime.tv_sec'] +
$wgRUstart['ru_utime.tv_usec'] / 1e6
;
484 if ( $metric === 'cpu' ) {
485 # This is the time of system calls, added to the user time
486 # it gives the total CPU time
487 $time +
= $wgRUstart['ru_stime.tv_sec'] +
$wgRUstart['ru_stime.tv_usec'] / 1e6
;
491 if ( empty( $wgRequestTime ) ) {
494 return $wgRequestTime;
499 protected function collateData() {
500 if ( $this->mCollateDone
) {
503 $this->mCollateDone
= true;
507 $this->mCollated
= array();
508 $this->mCalls
= array();
509 $this->mMemory
= array();
511 # Estimate profiling overhead
512 $profileCount = count( $this->mStack
);
513 self
::calculateOverhead( $profileCount );
515 # First, subtract the overhead!
516 $overheadTotal = $overheadMemory = $overheadInternal = array();
517 foreach ( $this->mStack
as $entry ) {
521 $elapsed = $end - $start;
522 $memory = $entry[5] - $entry[3];
524 if ( $fname == '-overhead-total' ) {
525 $overheadTotal[] = $elapsed;
526 $overheadMemory[] = $memory;
527 } elseif ( $fname == '-overhead-internal' ) {
528 $overheadInternal[] = $elapsed;
531 $overheadTotal = $overheadTotal ?
array_sum( $overheadTotal ) / count( $overheadInternal ) : 0;
532 $overheadMemory = $overheadMemory ?
array_sum( $overheadMemory ) / count( $overheadInternal ) : 0;
533 $overheadInternal = $overheadInternal ?
array_sum( $overheadInternal ) / count( $overheadInternal ) : 0;
536 foreach ( $this->mStack
as $index => $entry ) {
540 $elapsed = $end - $start;
542 $memory = $entry[5] - $entry[3];
543 $subcalls = $this->calltreeCount( $this->mStack
, $index );
545 if ( !preg_match( '/^-overhead/', $fname ) ) {
546 # Adjust for profiling overhead (except special values with elapsed=0
548 $elapsed -= $overheadInternal;
549 $elapsed -= ( $subcalls * $overheadTotal );
550 $memory -= ( $subcalls * $overheadMemory );
554 if ( !array_key_exists( $fname, $this->mCollated
) ) {
555 $this->mCollated
[$fname] = 0;
556 $this->mCalls
[$fname] = 0;
557 $this->mMemory
[$fname] = 0;
558 $this->mMin
[$fname] = 1 << 24;
559 $this->mMax
[$fname] = 0;
560 $this->mOverhead
[$fname] = 0;
563 $this->mCollated
[$fname] +
= $elapsed;
564 $this->mCalls
[$fname]++
;
565 $this->mMemory
[$fname] +
= $memory;
566 $this->mMin
[$fname] = min( $this->mMin
[$fname], $elapsed );
567 $this->mMax
[$fname] = max( $this->mMax
[$fname], $elapsed );
568 $this->mOverhead
[$fname] +
= $subcalls;
571 $this->mCalls
['-overhead-total'] = $profileCount;
572 arsort( $this->mCollated
, SORT_NUMERIC
);
576 * Returns a list of profiled functions.
580 function getFunctionReport() {
581 $this->collateData();
584 $nameWidth = $width - 65;
585 $format = "%-{$nameWidth}s %6d %13.3f %13.3f %13.3f%% %9d (%13.3f -%13.3f) [%d]\n";
586 $titleFormat = "%-{$nameWidth}s %6s %13s %13s %13s %9s\n";
587 $prof = "\nProfiling data\n";
588 $prof .= sprintf( $titleFormat, 'Name', 'Calls', 'Total', 'Each', '%', 'Mem' );
590 $total = isset( $this->mCollated
['-total'] ) ?
$this->mCollated
['-total'] : 0;
592 foreach ( $this->mCollated
as $fname => $elapsed ) {
593 $calls = $this->mCalls
[$fname];
594 $percent = $total ?
100. * $elapsed / $total : 0;
595 $memory = $this->mMemory
[$fname];
596 $prof .= sprintf( $format,
597 substr( $fname, 0, $nameWidth ),
599 (float)( $elapsed * 1000 ),
600 (float)( $elapsed * 1000 ) / $calls,
603 ( $this->mMin
[$fname] * 1000.0 ),
604 ( $this->mMax
[$fname] * 1000.0 ),
605 $this->mOverhead
[$fname]
608 $prof .= "\nTotal: $total\n\n";
614 * Dummy calls to wfProfileIn/wfProfileOut to calculate its overhead
616 protected static function calculateOverhead( $profileCount ) {
617 wfProfileIn( '-overhead-total' );
618 for ( $i = 0; $i < $profileCount; $i++
) {
619 wfProfileIn( '-overhead-internal' );
620 wfProfileOut( '-overhead-internal' );
622 wfProfileOut( '-overhead-total' );
626 * Counts the number of profiled function calls sitting under
627 * the given point in the call graph. Not the most efficient algo.
629 * @param $stack Array:
630 * @param $start Integer:
634 function calltreeCount( $stack, $start ) {
635 $level = $stack[$start][1];
637 for ( $i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i-- ) {
644 * Log the whole profiling data into the database.
646 public function logData() {
647 global $wgProfilePerHost, $wgProfileToDatabase;
649 # Do not log anything if database is readonly (bug 5375)
650 if ( wfReadOnly() ||
!$wgProfileToDatabase ) {
654 $dbw = wfGetDB( DB_MASTER
);
655 if ( !is_object( $dbw ) ) {
659 if ( $wgProfilePerHost ) {
660 $pfhost = wfHostname();
666 $this->collateData();
668 foreach ( $this->mCollated
as $name => $elapsed ) {
669 $eventCount = $this->mCalls
[$name];
670 $timeSum = (float)( $elapsed * 1000 );
671 $memorySum = (float)$this->mMemory
[$name];
672 $name = substr( $name, 0, 255 );
675 $timeSum = $timeSum >= 0 ?
$timeSum : 0;
676 $memorySum = $memorySum >= 0 ?
$memorySum : 0;
678 $dbw->update( 'profiling',
680 "pf_count=pf_count+{$eventCount}",
681 "pf_time=pf_time+{$timeSum}",
682 "pf_memory=pf_memory+{$memorySum}",
686 'pf_server' => $pfhost,
690 $rc = $dbw->affectedRows();
692 $dbw->insert( 'profiling', array( 'pf_name' => $name, 'pf_count' => $eventCount,
693 'pf_time' => $timeSum, 'pf_memory' => $memorySum, 'pf_server' => $pfhost ),
694 __METHOD__
, array( 'IGNORE' ) );
696 // When we upgrade to mysql 4.1, the insert+update
697 // can be merged into just a insert with this construct added:
698 // "ON DUPLICATE KEY UPDATE ".
699 // "pf_count=pf_count + VALUES(pf_count), ".
700 // "pf_time=pf_time + VALUES(pf_time)";
702 } catch ( DBError
$e ) {}
706 * Get the function name of the current profiling section
709 function getCurrentSection() {
710 $elt = end( $this->mWorkStack
);
715 * Add an entry in the debug log file
717 * @param string $s to output
719 function debug( $s ) {
720 if ( function_exists( 'wfDebug' ) ) {
726 * Add an entry in the debug log group
728 * @param string $group Group to send the message to
729 * @param string $s to output
731 function debugGroup( $group, $s ) {
732 if ( function_exists( 'wfDebugLog' ) ) {
733 wfDebugLog( $group, $s );
738 * Get the content type sent out to the client.
739 * Used for profilers that output instead of store data.
742 protected function getContentType() {
743 foreach ( headers_list() as $header ) {
744 if ( preg_match( '#^content-type: (\w+/\w+);?#i', $header, $m ) ) {